package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.ArticleVisitStreamMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    private final static Short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper articleMapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ArticleFreemarkerService articleFreemarkerService;

    @Autowired
    private CacheService cacheService;

    /**
     * 加载文章列表
     * @param articleHomeDto
     * @param type 1-加载更多 2-加载最新
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto articleHomeDto, Short type) {

        // 效验参数
        // 分页条数效验
        Integer size = articleHomeDto.getSize();
        if(size == null || size == 0) {
            size = 10;
        }
        // 分页的值不超过50
        size = Math.min(size, MAX_PAGE_SIZE);

        // 效验参数 --> type
        if(!type.equals(ArticleConstants.LOADTYPE_LOAD_MORE) && !type.equals(ArticleConstants.LOADTYPE_LOAD_NEW)) {
            type = ArticleConstants.LOADTYPE_LOAD_MORE;
        }

        // 频道参数效验
        if(StringUtils.isBlank(articleHomeDto.getTag())) {
            articleHomeDto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        // 时间效验
        if(articleHomeDto.getMaxBehotTime() == null) {
            articleHomeDto.setMaxBehotTime(new Date());
        }

        if(articleHomeDto.getMinBehotTime() == null) {
            articleHomeDto.setMinBehotTime(new Date());
        }

        // 查询
        List<ApArticle> apArticles = articleMapper.loadArticleList(articleHomeDto, type);
        // 结果返回
        return ResponseResult.okResult(apArticles);
    }

    /**
     * 保存app端相关文章
     * @param articleDto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto articleDto) {

        /*try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }*/

        // 检查参数
        if(articleDto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(articleDto, apArticle);

        // 判断是否存在id
        if(articleDto.getId() == null) {
            // 不存在id 保存 文章 文章配置 文章内容
            // 保存文章
            save(apArticle);

            // 保存配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            // 保存文章内容
            ApArticleContent articleContent = new ApArticleContent();
            articleContent.setArticleId(apArticle.getId());
            articleContent.setContent(articleDto.getContent());
            apArticleContentMapper.insert(articleContent);
        } else {
            // 存在id 修改 文章 文章内容
            // 修改文章
            updateById(apArticle);

            // 修改文章内容
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery().eq(ApArticleContent::getArticleId, articleDto.getId()));
            apArticleContent.setContent(articleDto.getContent());
            apArticleContentMapper.updateById(apArticleContent);
        }

        // 异步调用生成静态文件上传到minio中
        articleFreemarkerService.buildArticleToMinio(apArticle, articleDto.getContent());

        // 结果返回 文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 查看文章，数据回显
     * @param articleInfoDto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto articleInfoDto) {

        // 检查参数
        if(articleInfoDto == null || articleInfoDto.getArticleId() == null || articleInfoDto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        boolean isFollow = false, isLike = false, isUnLike = false, isCollection = false;

        ApUser user = AppThreadLocalUtil.getUser();
        if(user != null) {
            // 喜欢行为
            String likeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + articleInfoDto.getAuthorId().toString(), user.getId().toString());
            if(StringUtils.isNotBlank(likeBehaviorJson)) {
                isLike = true;
            }
            // 不喜欢行为
            String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + articleInfoDto.getAuthorId().toString(), user.getId().toString());
            if(StringUtils.isNotBlank(unLikeBehaviorJson)) {
                isUnLike = true;
            }
            // 是否收藏
            String collectionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), articleInfoDto.getArticleId().toString());
            if(StringUtils.isNotBlank(collectionJson)) {
                isCollection = true;
            }
            // 是否关注
            Double score = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), articleInfoDto.getAuthorId().toString());
            System.out.println(score);
            if(score != null) {
                isFollow = true;
            }
        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("isFollow", isFollow);
        resultMap.put("isLike", isLike);
        resultMap.put("isUnLike", isUnLike);
        resultMap.put("isCollection", isCollection);
        return ResponseResult.okResult(resultMap);
    }

    /**
     * 加载文章列表
     * @param articleHomeDto
     * @param type 1-加载更多 2-加载最新
     * @param firstPage true-首页 false-非首页
     * @return
     */
    @Override
    public ResponseResult load2(ArticleHomeDto articleHomeDto, Short type, boolean firstPage) {
        if(firstPage) {
            String jsonStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + articleHomeDto.getTag());
            if(StringUtils.isNotBlank(jsonStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(jsonStr, HotArticleVo.class);
                ResponseResult responseResult = ResponseResult.okResult(hotArticleVoList);
                return responseResult;
            }
        }
        return load(articleHomeDto, type);
    }

    /**
     * 更新文章的分值，同时更新缓存中的热点文章数据
     * @param articleVisitStreamMess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess articleVisitStreamMess) {

        // 更新文章的阅读、点赞、收藏、评论的数量
        ApArticle apArticle = updateArticle(articleVisitStreamMess);

        // 计算文章的分值
        Integer score = computeScore(apArticle);
        score = score * 3;

        // 替换当前文章对应频道的热点数据
        replaceToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + apArticle.getChannelId());

        // 替换推荐对应的热点数据
        replaceToRedis(apArticle, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 替换数据并且存入redis
     * @param apArticle
     * @param score
     * @param s
     */
    private void replaceToRedis(ApArticle apArticle, Integer score, String s) {
        String articleListStr = cacheService.get(s);
        if (StringUtils.isNotBlank(articleListStr)) {
            List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);

            boolean flag = true;

            // 如果缓存中存在该文章只更新分值
            for (HotArticleVo hotArticleVo : hotArticleVoList) {
                if (hotArticleVo.getId().equals(apArticle.getId())) {
                    hotArticleVo.setScore(score);
                    flag = false;
                    break;
                }
            }

            // 如果缓存中不存在，查询缓存中分值最小的一条数据，进行分值的比较，如果当前文章的分值大于缓存中的数据，就替换
            if (flag) {
                if (hotArticleVoList.size() >= 30) {
                    hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
                    HotArticleVo lastHot = hotArticleVoList.get(hotArticleVoList.size() - 1);
                    if (lastHot.getScore() < score) {
                        hotArticleVoList.remove(lastHot);
                        HotArticleVo hotArticleVo = new HotArticleVo();
                        BeanUtils.copyProperties(apArticle, hotArticleVo);
                        hotArticleVo.setScore(score);
                        hotArticleVoList.add(hotArticleVo);
                    }
                } else {
                    HotArticleVo hotArticleVo = new HotArticleVo();
                    BeanUtils.copyProperties(apArticle, hotArticleVo);
                    hotArticleVo.setScore(score);
                    hotArticleVoList.add(hotArticleVo);
                }
            }

            // 缓存到redis
            hotArticleVoList = hotArticleVoList.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
            cacheService.set(s, JSON.toJSONString(hotArticleVoList));
        }
    }

    /**
     * 更新文章行为数量
     * @param articleVisitStreamMess
     */
    private ApArticle updateArticle(ArticleVisitStreamMess articleVisitStreamMess) {
        ApArticle apArticle = getById(articleVisitStreamMess.getArticleId());
        apArticle.setCollection(apArticle.getCollection() == null ? 0 : apArticle.getCollection() + articleVisitStreamMess.getCollect());
        apArticle.setComment(apArticle.getComment() == null ? 0 : apArticle.getComment() + articleVisitStreamMess.getComment());
        apArticle.setLikes(apArticle.getLikes() == null ? 0 : apArticle.getLikes() + articleVisitStreamMess.getLike());
        apArticle.setViews(apArticle.getViews() == null ? 0 : apArticle.getViews() + articleVisitStreamMess.getView());
        updateById(apArticle);
        return apArticle;
    }

    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if(apArticle.getLikes() != null){
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            score += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
